package nero.yncc.com.createart.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import nero.yncc.com.createart.R;
import nero.yncc.com.createart.activity.ActivityArticleList;
import nero.yncc.com.createart.activity.ActivitySiteMessage;
import nero.yncc.com.createart.adapter.AdapterFoundArticle;
import nero.yncc.com.createart.base.BaseFragment;
import nero.yncc.com.createart.base.Constants;
import nero.yncc.com.createart.bean.BeanAd;
import nero.yncc.com.createart.bean.BeanArticle;
import nero.yncc.com.createart.bean.BeanArticleType;
import nero.yncc.com.createart.bean.BeanMessage;
import nero.yncc.com.createart.utils.HttpUtils;
import nero.yncc.com.createart.utils.TextUtil;
import nero.yncc.com.createart.utils.UserDataUtil;

/**
 * Created by nero on 17-6-22.
 */

@ContentView(R.layout.fragment_found)
public class FragmentFound extends BaseFragment {


    @ViewInject(R.id.pl_rticle)
    PullToRefreshListView pl_rticle;

    ViewPager vp_main;
    LinearLayout ll_dom;
    RelativeLayout rl_dom;

    View view_red;

    ArrayList<BeanMessage> arrayList_article;
    AdapterFoundArticle adapterFoundArticle;

    ImageView iv_site_message;
    TextView tv_site_message;

    ImageView iv_zhinan;
    TextView tv_zhinan;
    ImageView iv_hot;
    TextView tv_hot;
    ImageView iv_bt;
    TextView tv_bt;

    int pageSize = 10, page = 1;
    boolean canLoad;

    ArrayList<BeanAd> arrayList_ad;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = x.view().inject(this, inflater, container);
        initAll();

        return view;
    }

    @Override
    protected void initView() {

        View view = LayoutInflater.from(getContext()).inflate(R.layout.head_found, null);
        vp_main = view.findViewById(R.id.vp_main);
        ll_dom = view.findViewById(R.id.ll_dom);
        rl_dom = view.findViewById(R.id.rl_dom);

        iv_site_message = view.findViewById(R.id.iv_site_message);
        tv_site_message = view.findViewById(R.id.tv_site_message);
        iv_zhinan = view.findViewById(R.id.iv_zhinan);
        tv_zhinan = view.findViewById(R.id.tv_zhinan);
        tv_hot = view.findViewById(R.id.tv_hot);
        iv_hot = view.findViewById(R.id.iv_hot);
        tv_bt = view.findViewById(R.id.tv_bt);
        iv_bt = view.findViewById(R.id.iv_bt);

        pl_rticle.getRefreshableView().addHeaderView(view);

        pl_rticle.setMode(PullToRefreshBase.Mode.BOTH);

    }

    @Override
    protected void initData() {
        arrayList_ad = new ArrayList<>();

        //场景套餐
        arrayList_article = new ArrayList<>();
        adapterFoundArticle = new AdapterFoundArticle(mContext, arrayList_article);
        pl_rticle.setAdapter(adapterFoundArticle);

        setListViewHeight();

    }

    @Override
    protected void getHttpData() {
        super.getHttpData();


    }

    @Override
    protected void doClick(int id) {
        super.doClick(id);
        switch (id) {
            case R.id.tv_site_message:
            case R.id.iv_site_message:
                Intent intent_site = new Intent(mContext, ActivitySiteMessage.class);
                startActivity(intent_site);
                break;
            case R.id.iv_zhinan:
            case R.id.tv_zhinan:
                if (TextUtils.isEmpty(Constants.hashmap_type.get("家具指南"))) {
                    showToast("尚未添加该分类");
                    return;
                }
                Intent intent_zhinan = new Intent(mContext, ActivityArticleList.class);
                intent_zhinan.putExtra("id",Constants.hashmap_type.get("家具指南"));
                intent_zhinan.putExtra("title","家具指南");
                startActivity(intent_zhinan);
                break;
            case R.id.tv_hot:
            case R.id.iv_hot:
                if (TextUtils.isEmpty(Constants.hashmap_type.get("火热活动"))) {
                    showToast("尚未添加该分类");
                    return;
                }
                Intent intent_hot = new Intent(mContext, ActivityArticleList.class);
                intent_hot.putExtra("id",Constants.hashmap_type.get("火热活动"));
                intent_hot.putExtra("title","火热活动");
                startActivity(intent_hot);
                break;
            case R.id.tv_bt:
            case R.id.iv_bt:
                if (TextUtils.isEmpty(Constants.hashmap_type.get("最美样板"))) {
                    showToast("尚未添加该分类");
                    return;
                }

                Intent intent_bt = new Intent(mContext, ActivityArticleList.class);
                intent_bt.putExtra("id",Constants.hashmap_type.get("最美样板"));
                intent_bt.putExtra("title","最美样板");
                startActivity(intent_bt);

                break;

        }
    }

    private void initViewPager() {
        final int page = arrayList_ad.size();//总的viewpage数量

        if (page > 1) {
            for (int a = 0; a < page; a++) {
                View views = LinearLayout.inflate(mContext, R.layout.view_dom, null);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
                params.setMargins(5, 5, 5, 5);
                views.setLayoutParams(params);
                ll_dom.addView(views);

            }

            view_red = LinearLayout.inflate(mContext, R.layout.view_dom, null);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(15, 15);
            params.setMargins(5, 5, 5, 5);
            view_red.setLayoutParams(params);
            view_red.setBackgroundResource(R.drawable.tv_dom);
            params.addRule(RelativeLayout.ALIGN_LEFT, R.id.ll_dom);
            rl_dom.addView(view_red);
        }
        vp_main.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view_red.getLayoutParams();
                //70为一个

                params.setMargins((int) (25 * (positionOffset) + 25 * position) + 5, 5, 5, 5);
                view_red.setLayoutParams(params);
                view_red.setBackgroundResource(R.drawable.tv_dom);
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        vp_main.setAdapter(new FragmentPagerAdapter(this.getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                FragmentFoundAd fragmentFoundAd = new FragmentFoundAd();
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", arrayList_ad.get(position));
                fragmentFoundAd.setArguments(bundle);
                return fragmentFoundAd;
            }

            @Override
            public int getCount() {
                return page;
            }
        });
    }

    @Override
    protected void initListener() {
        super.initListener();
        pl_rticle.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                canLoad = true;
                arrayList_article.clear();
                adapterFoundArticle.notifyDataSetChanged();

                getData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                getData();
            }
        });
        pl_rticle.setRefreshing(true);
        iv_site_message.setOnClickListener(this);
        tv_site_message.setOnClickListener(this);
        iv_zhinan.setOnClickListener(this);
        tv_zhinan.setOnClickListener(this);
        tv_hot.setOnClickListener(this);
        iv_hot.setOnClickListener(this);
        tv_bt.setOnClickListener(this);
        iv_bt.setOnClickListener(this);

    }


    public void setListViewHeight() {

        if (adapterFoundArticle.viewHeight == 0) {
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    if (FragmentFound.this.getActivity() != null) {
                        FragmentFound.this.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setListViewHeight();
                            }
                        });
                    }
                }
            }, 500);
            return;
        }

        if (pl_rticle == null) {
            return;
        }

        if (adapterFoundArticle == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < adapterFoundArticle.getCount(); i++) {
            totalHeight += adapterFoundArticle.viewHeight;
        }
        ViewGroup.LayoutParams params = pl_rticle.getLayoutParams();
        params.height = totalHeight;
        pl_rticle.setLayoutParams(params);
    }

    private void getAd() {
        HashMap<String, String> hashMap = new HashMap<>();
        new HttpUtils().get(getActivity(), Constants.API_FOUND_AD, hashMap, null, HttpUtils.TYPE_ARRAY, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                JSONArray jsonArray = (JSONArray) json;
                for (int a = 0; a < jsonArray.length(); a++) {
                    try {
                        arrayList_ad.add(JSON.parseObject(jsonArray.getString(a), BeanAd.class));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
//
                initViewPager();
            }

            @Override
            public void fail(String failMsg) {

            }
        });

    }

    @Override
    protected void getData() {
        super.getData();
        if (Constants.hashmap_type.size() == 0) {
            UserDataUtil.getArticleType(getActivity());
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            getData();
                        }
                    });

                }
            }, 1000);
            return;
        }

        String foundId = Constants.hashmap_type.get("发现");
        if (TextUtils.isEmpty(foundId)) {
            showToast("暂无发现分类");
            return;
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("pagesize", pageSize + "");
        hashMap.put("pageindex", page + "");
        hashMap.put("category_id", foundId);

//        "count":149,
//                "list":[
        HttpUtils.get(getActivity(), Constants.API_ARTICLE_LIST, hashMap, null, HttpUtils.TYPE_NOTHING, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                JSONArray jsonArray = null;

                try {
                    jsonArray = new JSONObject(json.toString()).getJSONArray("list");
                    if (!canLoad) {
                        showToast("没有更多内容了");
                        pl_rticle.onRefreshComplete();
                        return;
                    }
                    if (jsonArray.length() < pageSize) {
                        canLoad = false;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("获取列表失败，请再次尝试");
                    return;
                }


                for (int a = 0; a < jsonArray.length(); a++) {
                    try {
                        arrayList_article.add(JSON.parseObject(jsonArray.getString(a), BeanMessage.class));

                    } catch (Exception e) {

                    }
                }

                adapterFoundArticle.notifyDataSetChanged();
                pl_rticle.onRefreshComplete();
                setListViewHeight();
                if (arrayList_ad.size() <= 0) {
                    getAd();
                }
            }

            @Override
            public void fail(String failMsg) {
                showToast(failMsg);
                pl_rticle.onRefreshComplete();
            }
        });

    }

}
